﻿using System;
using System.Windows;
using SW = System.Windows;
using System.Windows.Controls;
using MultiViewer.Network;
using System.Windows.Media;
using System.Threading;
using System.Windows.Input;
using System.Diagnostics;
using System.Windows.Media.Imaging;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Windows.Documents;

namespace MultiViewer.Display
{
    public class StreamImageViewer : Grid
    {
        private Rect rc;

        private Node node;
        public StreamImageViewer(Rect rc)
        {
            VerticalAlignment = VerticalAlignment.Stretch;
            HorizontalAlignment = HorizontalAlignment.Stretch;
            Background = Brushes.Black;
            SnapsToDevicePixels = true;
            this.rc = rc;

        }

        public void AttachNode(Node node)
        {
            this.node = node;
            node.AddTransactionHandler<ShowImageStream, ShowImageStreamTransactionState>(Dispatcher,
                ShowImagePrepareHandler,
                ShowImageCommitHandler,
                ShowImageRollbackHandler);
        }

        public void DetachNode()
        {
            node = null;
            // TODO: Detach handlers
        }

        private void ShowImagePrepareHandler(ShowImageStream request, HandlerResult<ShowImageStreamTransactionState> result)
        {
            try {
                 JpegBitmapDecoder jdec = new JpegBitmapDecoder(new MemoryStream(request.ImageStream),
                     BitmapCreateOptions.None, BitmapCacheOption.Default);
                int w = jdec.Frames[0].PixelWidth;
                int h = jdec.Frames[0].PixelHeight;
                result.SetSuccess(new ShowImageStreamTransactionState(request,                   
                    new CroppedBitmap(jdec.Frames[0],
                        new Int32Rect((int)(w * rc.Left), (int)(h*rc.Top),
                            (int)(w*rc.Width),(int)(h*rc.Height)))));
            }
            catch (Exception exc)
            {
                result.SetFailure(exc);
            }
        }

        private void ShowImageCommitHandler(ShowImageStreamTransactionState state)
        {
            Children.Clear();
            Image img = new Image();
            img.VerticalAlignment = VerticalAlignment.Stretch;
            img.HorizontalAlignment = HorizontalAlignment.Stretch;
            img.Source = state.Bitmap;
            img.Stretch = Stretch.Fill;
            Children.Add(img);
        }

        private void ShowImageRollbackHandler(ShowImageStreamTransactionState state)
        {

        }
    }
}